<script setup>
import {ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
  groupName: {
    type: String,
    default: '',
    required: true
  },
  sortNum: {
    type: Number,
    default: 1,
    required: true
  },
})

const form = ref({
  id: -1,
  name: '',
  sort_num: '',
})

const rules = ref({
  name: [
    {required: true, message: '分组名称不能为空', trigger: 'blur'}
  ],
  sort_num: [
    {required: true, message: '分组名称不能为空', trigger: 'blur'}
  ]
})

const formRef = ref(null)

const emits = defineEmits(['update:modelValue', 'initGroupData'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log(form.value, '-------------------------.valueform.valueform.value')
      let res = await requestUtil.post('monitor_alert/group/action', form.value);
      let data = res.data;
      if (data.code === 200) {
        ElMessage.success('执行成功')
        formRef.value.resetFields()
        emits('initGroupData')
        handleClose()
      } else {
        ElMessage.error(data.msg)
      }
    } else {
      console.log('fail')
    }
  })
}

watch(
    () => props.dialogVisible,
    () => {
      form.value.id = props.id;
      form.value.name = props.groupName;
      form.value.sort_num = props.sortNum;
    }
)
</script>

<template>
  <el-dialog
      model-value="dialogVisible"
      :title="props.dialogTitle"
      width="400px"
      style="padding: 40px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="分组名称:" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="显示顺序:" prop="sort_num">
        <el-input-number v-model="form.sort_num" :min="1" label="显示顺序"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>